package com.heimdallr.config;

import com.heimdallr.rbac.permission.dao.PermissionDao;
import com.heimdallr.rbac.permission.entity.*;
import com.heimdallr.rbac.user.dao.UserDao;
import com.heimdallr.util.AppUtils;
import com.heimdallr.util.cache.CachePool;
import com.heimdallr.util.RedisKey;
import com.heimdallr.util.cache.LocalCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.management.relation.Role;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 *
 * @author panxl
 * @date 2016/4/26
 */
@Component
public class RollingJob {

    private final static Logger logger = LoggerFactory.getLogger(RollingJob.class);
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private UserDao userDao;

    @Value("${shiroDemo.init}")
    private String init;

    @Scheduled(cron = "00 30 00 * * ?")
    public void dailyCatch() {
        CachePool.getInstance().getCache(CachePool.cacheKind.dataCache).clear();
        CachePool.getInstance().getCache(CachePool.cacheKind.userCache).clear();
        redisTemplate.delete(RedisKey.userEntity.name());
        logger.info("clear dataCache!");
    }

    @PostConstruct
    public void init(){

        if(AppUtils.isNotNull(init)&&"true".equals(init.trim())){
            //do init
            initMenu();
            initPermission();
            initRole();
            initGroup();
            initUser();
        }

    }

    private void initMenu(){

        redisTemplate.delete(RedisKey.menuEntity.name());

        List<MenuEntity> menuEntityList = new ArrayList<>();

        menuEntityList.add(new MenuEntity(1,0,"系统管理",""));
        menuEntityList.add(new MenuEntity(101,1,"用户管理","/user/index"));
        menuEntityList.add(new MenuEntity(102,1,"权限管理","/permission/index"));
        menuEntityList.add(new MenuEntity(103,1,"角色管理","/permission/role"));

        menuEntityList.forEach(entity->permissionDao.saveMenuEntity(entity));
    }

    public void initPermission(){

        redisTemplate.delete(RedisKey.permissionEntity.name());

        List<PermissionEntity> permissionEntityList = new ArrayList<>();

        permissionEntityList.add(new PermissionEntity(1,"权限__获取菜单","permission:menu_data","/permission/getMenu",2));
        permissionEntityList.add(new PermissionEntity(2,"权限__权限页面","permission:index_view","/permission/index",1));
        permissionEntityList.add(new PermissionEntity(3,"权限__权限页面数据","permission:getList_data","/permission/getList",2));
        permissionEntityList.add(new PermissionEntity(4,"权限__新增权限数据","permission:add_data","/permission/add",2));
        permissionEntityList.add(new PermissionEntity(5,"权限__角色__角色页面","permission:role_view","/permission/role",1));
        permissionEntityList.add(new PermissionEntity(6,"权限__角色__角色页面数据","permission:getRoleList_data","/permission/getRoleList",2));
        permissionEntityList.add(new PermissionEntity(7,"权限__角色__获取角色实体类","permission:getRoleEntity_data","/permission/getRoleEntity",2));
        permissionEntityList.add(new PermissionEntity(8,"权限__角色__编辑角色拥有的菜单","permission:editRoleHasMenu_data","/permission/editRoleHasMenu",2));
        permissionEntityList.add(new PermissionEntity(9,"权限__角色__编辑角色拥有的权限","permission:editRoleHasPerm_data","/permission/editRoleHasPerm",1));
        permissionEntityList.add(new PermissionEntity(10,"权限__菜单__获取所有菜单","permission:getAllMenu_data","/permission/getAllMenu",2));
        permissionEntityList.add(new PermissionEntity(11,"用户__用户页面","user:index_view","user:index_view/user/index",1));
        permissionEntityList.add(new PermissionEntity(12,"用户__用户页面数据","user:getList_data","/user/getList",2));

        permissionEntityList.forEach(entity->permissionDao.savePermissionEntity(entity));
    }

    private void initRole(){

        redisTemplate.delete(RedisKey.roleEntity.name());

        List<MenuEntity> allMenu = permissionDao.getAllMenuList();
        List<PermissionEntity> allPermissionEntity = permissionDao.getAllPermissionEntity();

        List<Integer> menuIds = allMenu.stream().mapToInt(MenuEntity::getId).collect(ArrayList::new,ArrayList::add,ArrayList::addAll);
        List<Integer> permissionIds = allPermissionEntity.stream().mapToInt(PermissionEntity::getId).collect(ArrayList::new,ArrayList::add,ArrayList::addAll);

        RoleEntity roleEntity = new RoleEntity();
        roleEntity.setId(1);
        roleEntity.setRoleName("super");
        roleEntity.setMenuIds(menuIds);
        roleEntity.setPermissionIds(permissionIds);
        roleEntity.setPermissionEntityList(allPermissionEntity);
        roleEntity.setMenuEntityList(allMenu);
        permissionDao.saveRoleEntity(roleEntity);
    }

    private void initGroup(){

        redisTemplate.delete(RedisKey.groupEntity.name());

        GroupEntity groupEntity = new GroupEntity();

        List<Integer> roleIds = new ArrayList<>();
        roleIds.add(1);

        List<RoleEntity> roleEntityList = new ArrayList<>();
        roleIds.forEach(roleId->roleEntityList.add(permissionDao.getRoleEntityById(roleId)));


        groupEntity.setId(1);
        groupEntity.setName("管理员组");
        groupEntity.setRoleEntityList(roleEntityList);
        groupEntity.setRoleIdList(roleIds);
        permissionDao.saveGroupEntity(groupEntity);
    }

    private void initUser(){

        redisTemplate.delete(RedisKey.userEntity.name());

        UserEntity userEntity = new UserEntity();
        userEntity.setUserName("admin");
        try {
            userEntity.setPassword(AppUtils.md5Encode(AppUtils.md5Encode("admin")));
        } catch (Exception e) {
            e.printStackTrace();
            //admin 两边md5加密的字符串
            userEntity.setPassword("c3284d0f94606de1fd2af172aba15bf3");
        }
        userEntity.setStatus(1);
        GroupEntity groupEntity = userDao.getGroupEntityById(1);
        userEntity.setGroupId(groupEntity.getId());
        userEntity.setGroupEntity(groupEntity);
        userDao.saveUserEntity(userEntity);
    }

}
